import views from 'koa-views' // 引入模板渲染中间件
import nunjucks from 'nunjucks' // 引入模板解析模块
import minifier from 'html-minifier' // 引入压缩html代码模块

import config from '../../config' // 引入配置
import utils from '../utils' // 引入工具类

export const index = app => {
  // 挂载模板引擎
  const templatePath = utils.resolve(`src/view/${config.theme}`)
  const nunjucksEnv = nunjucks.configure(templatePath, {
    trimBlocks: true,
    lstripBlocks: true,
    watch: true
  })
  app.use(views(templatePath, {
    options: {
      nunjucksEnv: nunjucksEnv
    },
    extension: 'html',
    map: { html: 'nunjucks' }
  }))

  // 中间件拦截处理压缩
  app.use(async(ctx, next) => {
    var nunjucksRender = ctx.render;
    ctx.render = async(relPath, locals = {}) => {
      await nunjucksRender(relPath, locals)
        .then(res => {
          ctx.body = minifier.minify(ctx.body, {
            removeComments: true,
            collapseWhitespace: true,
            minifyJS: true,
            minifyCSS: true
          })
        })
    }
    await next()
  })
}
